package com.ssau.expert.gui.user;

import com.ssau.expert.app.AppConfig;
import com.ssau.expert.common.Question;
import com.ssau.expert.common.QuestionRequestListener;
import com.ssau.expert.gui.app.Locator;
import com.ssau.expert.gui.common.Controller;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.List;

/**
 * Author: 345
 * Date: 09.10.13 18:26
 */
public class UserFrame extends JFrame implements UserPresenter, QuestionRequestListener {

    private static final String NAME = "ЭС. Режим пользователя.";

    private static final Dimension SIZE = new Dimension(400, 600);

    private UserFrame() {
    }

    @Override
    public void init() {

        initDisposition();
        initComponents();
    }

    @Override
    public String onQuestionRequest(Question question, boolean askFirstTime) {
        if (!askFirstTime) {
            showMessageDialog("Внимание", "Некорректный тип введенных данных");
        }
        String answer = showInputDialog("Необходим ответ на вопрос", question.getQuestionString());
        if (answer == null) {
            showMessageDialog("Консультация будет прервана");
            return null;
        }
        return answer;
    }

    private void initComponents() {
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        JPanel profilePanel = new JPanel();
        profilePanel.setBorder(BorderFactory.createTitledBorder("Профиль"));
        profilePanel.setLayout(new BoxLayout(profilePanel, BoxLayout.Y_AXIS));
        profilePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        profileJTextField = new JTextField();
        profileJTextField.setFocusable(false);
        profileJTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
        profilePanel.add(profileJTextField);
        add(profilePanel);

        // userEntredPanel.add(new JLabel("Автономность"));
        JPanel distancePanel = new JPanel();
        distancePanel.setBorder(BorderFactory.createTitledBorder("Автономность"));
        distancePanel.setLayout(new BoxLayout(distancePanel, BoxLayout.Y_AXIS));
        distancePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        distanceJTextField = new JTextField();
        distanceJTextField.setFocusable(false);
        distanceJTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
        distancePanel.add(distanceJTextField);
        add(distancePanel);

        // userEntredPanel.add(new Label("Экипаж"));

        JPanel staffPanel = new JPanel();
        staffPanel.setBorder(BorderFactory.createTitledBorder("Экипаж"));
        staffPanel.setLayout(new BoxLayout(staffPanel, BoxLayout.Y_AXIS));
        staffPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        staffJTextField = new JTextField();
        staffJTextField.setFocusable(false);
        staffJTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
        staffPanel.add(staffJTextField);
        add(staffPanel);

        //  add(userEntredPanel);

       /* JPanel toProvePanel = new JPanel();

        toProvePanel.setBorder(BorderFactory.createTitledBorder("Лог"));
        toProvePanel.setLayout(new BoxLayout(toProvePanel, BoxLayout.Y_AXIS));
        toProvePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        toProveJTextArea = new JTextArea();
        toProveJTextArea.setSize(toProvePanel.getSize());
        toProveJTextArea.setAlignmentX((Component.CENTER_ALIGNMENT));
        toProveJTextArea.setFocusable(false);
        JScrollPane jsc = new JScrollPane(toProveJTextArea);
        //jsc.setLayout(new BoxLayout(jsc,BoxLayout.Y_AXIS));
        jsc.setAlignmentX(Component.CENTER_ALIGNMENT);
        toProvePanel.add(jsc);
        add(toProvePanel);         */

        JPanel result = new JPanel();
        result.setBorder(BorderFactory.createTitledBorder("Результат"));
        result.setLayout(new BoxLayout(result, BoxLayout.Y_AXIS));
        result.setAlignmentX(Component.CENTER_ALIGNMENT);
        // resultListModel = new DefaultListModel();
        // resList = new JList<>(resultListModel);
        //resList.setLayoutOrientation(JList.VERTICAL);
        //  resList.setSize(100,100);
        //   resList.setAlignmentX(Component.CENTER_ALIGNMENT);
        //   result.add(resList);
        resultTextArea = new JTextArea();
        resultTextArea.setAlignmentX(Component.CENTER_ALIGNMENT);
        resultTextArea.setFocusable(false);
        result.add(resultTextArea);
        add(result);

        startConsultationJButton = new JButton("Консультация");
        startConsultationJButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(startConsultationJButton);
        startConsultationJButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                displayUserInput("", "", "");
                resultTextArea.setText("");
                startConsultation();
            }
        });

        logButton = new JButton("Объяснение решения");
        logButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(logButton);
        logButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                displayLog();
            }
        });

        helpButton = new JButton("Справка");
        helpButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        add(helpButton);
        helpButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                displayHelp();
            }
        });


    }

    private void displayHelp() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("help.txt"));
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Файл справки не неайден");
        }
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
            String everything = sb.toString();
            JOptionPane.showMessageDialog(this, everything, "Справка", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    private void initDisposition() {
        setSize(SIZE);
        setTitle(NAME);
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                Controller.get().showLoginFrame();
            }
        });
    }

    @Override
    public void showFrame() {
        setName(NAME);
        setTitle(NAME);
        setVisible(true);
    }

    @Override
    public void showMessageDialog(String title, String message) {
        JOptionPane.showMessageDialog(this, message, title, JOptionPane.INFORMATION_MESSAGE);
    }

    @Override
    public void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(this, message);
    }

    @Override
    public void addElementToResultList(String element) {
        resultTextArea.setText(resultTextArea.getText() + "\n" + element);
    }

    @Override
    public void displayUserInput(String shipProfileAnswer, String staffAnswer, String distanceAnswer) {
        profileJTextField.setText(shipProfileAnswer);
        distanceJTextField.setText(distanceAnswer);
        staffJTextField.setText(staffAnswer);
    }

    @Override
    public void clearResultListModel() {
        resultTextArea.setText("");
    }

    @Override
    public String showInputDialog(String questionString) {
        return JOptionPane.showInputDialog(this, questionString);
    }

    @Override
    public String showInputDialog(String title, String questionString) {
        return JOptionPane.showInputDialog(this, questionString, title, JOptionPane.INFORMATION_MESSAGE);
    }

    @Override
    public void displayLog() {
        List<String> log = Locator.getExpert().getLog();

        try {
            File f = new File(AppConfig.getLogFilePath());
            FileUtils.writeLines(f, log);
            List<String> logList = Locator.getExpert().getLog();
            String allLog = "";
            for (String str : logList) {
                allLog += "\n" + str;
            }
            //JOptionPane.showMessageDialog(this, allLog);
        } catch (IOException ex) {
            System.out.println("Catched IO ex while saving log.");
            System.out.println(ex.getMessage());
        }

        showMessageDialog(String.format("Лог работы системы сохранен в файл '%s'", AppConfig.getLogFilePath()));
    }

    private void startConsultation() {
        Controller.get().startConsultation();
    }

    private JButton startConsultationJButton;
    private JButton logButton;

    private JPanel userEntredPanel;
    private JTextField profileJTextField;
    private JTextField distanceJTextField;
    private JTextField staffJTextField;
    private JTextArea toProveJTextArea;
    private DefaultListModel<String> resultListModel;
    private JList<String> resList;
    private JTextArea resultTextArea;
    private JButton helpButton;

    private static UserFrame instance;

    public static UserFrame get() {
        if (instance == null) {
            instance = new UserFrame();
        }
        return instance;
    }
}
